<?php
/*
	XIAONEI app class model.
	by Alex,wu 
*/
class XiaoneiRestClient {
	  public $secret;
	  public $session_key;
	  public $api_key;
	  public $v;
	  public $server_addr;
	  public $method;
	  public $added;        // to save making the users.isAppAdded api call, this will get prepopulated on canvas pages
	public function __construct($api_key,$secret,$session_key=null) 
	{	
		
		$this->secret   = $secret;
		$this->api_key  = $api_key;
		$this->v='1.0';
		$this->session_key=$session_key;			
	    $this->server_addr='http://openapi.guanxi.koubei.com/openapi/openapi.php?';

	}
	/*
	public function createToken(){
		return $this->post_request('auth.createToken','');
	}
	*/
	public function auth($method)
	{
		$params=array();
		switch($method){
			case 'createToken':
			break;
			
			case 'getSession':
				$authTokenArray=self::auth('createToken');
				//print_r($authTokenArray);
				if($authTokenArray[0]&&$authTokenArray[0][0])
				{
					$authToken=$authTokenArray[0][0];
					$params['authToken']=$authToken;
				}else{
					return false;
				}
			break;
		}		
		$method='auth.'.$method;
		return $this->call_method($method,$params);
	}
	
	public function &users_isAppAdded($uid=null) {
    if (isset($this->added)) {
         return $this->added;
    }      
    $method='users.isAppAdded';
	$params['uid']=$uid;
    return $this->call_method($method,$params);
  }
   
  public function users($method,$array=array())
	{
		$params=array();
		switch($method){
			case 'getInfo':
				if($array['uids'])
				$params['uids']=$array['uids'];
				else $params['uids']=$_POST['yk_sig_user'];
				if($array['fields'])
				$params['fields']=$array['fields'];
			break;
			
			case 'getLoggedInUser':
			break;

			case 'isAppAdded':
				if($array['uid'])
				$params['uid']=$array['uid'];
			break;
		}		

		$method='users.'.$method;
		return $this->call_method($method,$params);
	}
	
	

	public function profile($method,$array=array())
	{
		$params=array();
		switch($method){
			case 'getXNML':
				if($array['uid'])
				$params['uid']=$array['uid'];
				else $params['uid']=$_POST['yk_sig_user'];
			break;
			
			case 'setXNML':
				if($array['uid'])
				$params['uid']=$array['uid'];
				if($array['profile'])
				$params['profile']=$array['profile'];
				if($array['profile_action'])
				$params['profile_action']=$array['profile_action'];
			break;

		}
		$method='profile.'.$method;	
		return $this->call_method($method,$params);
	}
	

	public function friends($method,$array=array())
	{
		$params=array();
		switch($method){
			case 'getFriends':
				if($array['page'])
				$params['page']=$array['page'];
				if($array['count'])
				$params['count']=$array['count'];
			break;
			
			case 'areFriends':
				if($array['uids1'])
				$params['uids1']=$array['uids1'];
				if($array['uids2'])
				$params['uids2']=$array['uids2'];	
			break;

			case "get":
                $params=array();		 		
			break;

			case 'getAppUsers':
			break;

			case 'getAppFriends':
				if(!empty($array['fields']))
					$params['fields']=$array['fields'];
            break;

		}		
		$method='friends.'.$method;
		return $this->call_method($method,$params);
	}	
	// feed
	public function feed($method,$array=array()){
		$params=array();
		switch($method){
			case 'publishTemplatizedAction':
				if($array['template_id']) //current user's friends' uids
				$params['template_id']=$array['template_id'];
				if($array['title_data'])
				$params['title_data']=$array['title_data'];
				if($array['body_data'])
				$params['body_data']=$array['body_data'];
				if($array['resource_id'])
				$params['resource_id']=$array['resource_id'];
			break;
		}
		$method='feed.'.$method;
		return $this->call_method($method,$params);
	}
		

	
	
	// function requests expires in 2008.07.08
	public function requests($method,$array=array())
	{
		$params=array();
		switch($method){
			case 'sendRequest':
				if($array['uids']) //current user's friends' uids
				$params['uids']=$array['uids'];
			break;

			case 'getOutsiteInvite':
				if($array['session_key'])
				$params['session_key']=$array['session_key'];
				if($array['uids'])
				$params['uids']=$array['uids'];
				if($array['format'])
				$params['format']=$array['format'];
			break;
		}
		$method='requests.'.$method;
	    return $this->call_method($method,$params);
	}
	
	//function notifications
	public function notifications($method,$array=array())
	{
		$params=array();
		switch($method){
			case 'send':
				if(isset($array['to_ids'])) //current user's friends' uids
				  $params['to_ids']=$array['to_ids'];
				if($array['notification'])
				  $params['notification']=$array['notification'];
			break;
		}

		$method='notifications.'.$method;		
		return $this->call_method($method,$params);
	}
			
	public function photos($method,$array=array())
	{
		$params=array();
		switch($method){
			case 'getAlbums':
				if($array['uid'])
				   $params['uid']=$array['uid'];
				else $params['uid']=$_POST['yk_sig_user'];
			break;
			
			case 'get':
			break;

		}
		$method='photos.'.$method;
		return $this->call_method($method,$params);
	}	

	public function messages($method,$array=array())
	{
		$params=array();
		switch($method){
			case 'gets':
				if($array['isInbox'])
				$params['isInbox']=$array['isInbox'];
				else $params['isInbox']=true;
			break;
			
			case 'get':
			break;
		}	
		$method='message.'.$method;	
		return $this->call_method($method,$params);
	}
	
	
	// zlj add 
	public function invitations($method,$array=array())
	{
        $params=array(); 
        switch($method){ 
			case 'getUserOsInviteCnt':
                if(isset($array['uids'])) 
                	$params['uids']=$array['uids']; 
			break; 

			case 'getIsInfo':
					if(isset($array['invite_ids'])) 
					$params['invite_ids']=$array['invite_ids']; 
			break; 

			case 'getOsInfo':
					if(isset($array['invite_ids'])) 
					$params['invite_ids']=$array['invite_ids']; 
			break; 

		} 

		$method='invitations.'.$method;	
		return $this->call_method($method,$params);
	}
		
	public function pay($method,$array=array())
	{
        $params=array(); 
        switch($method){ 
            case 'isCompleted': 
                if(isset($array['order_id'])) 
                	$params['order_id']=$array['order_id']; 
			break;
		
	    	case 'regOrder':
                if(isset($array['order_id'])) 
                	$params['order_id']=$array['order_id']; 
               	if(isset($array['amount'])) 
                	$params['amount']=$array['amount']; 
                if(isset($array['desc'])) 
                	$params['desc']=$array['desc']; 
            break; 
        } 

		$method='pay.'.$method;	
		return $this->call_method($method,$params);
	}
	
//=================================================================================================
    public function &call_method($method, $params) {
     //Check if we are in batch mode   
      $xml = $this->post_request($method, $params);
      //$xml = str_replace("&", "&amp;", $this->post_request($method, $params));

	  $result = $this->convert_xml_to_result($xml, $method, $params);
      if (is_array($result) && isset($result['error_code'])) {
        throw new XiaoneiRestClientException($result['error_msg'], $result['error_code']);
      }     
      return $result;
    }
	public static function generate_sig($params_array, $secret) {
			$str = '';
			ksort($params_array);
			// Note: make sure that the signature parameter is not already included in
			//       $params_array.
			foreach ($params_array as $k=>$v) {
			  $str .= "$k=$v";
			}
			$str .= $secret;
			return md5($str);
	 }		  	 
	 
	 private function create_post_string($method, $params) {
			$params['method'] = $method;
			$params['session_key'] = $this->session_key;
			$params['api_key'] = $this->api_key;
		    $params['format']='XML';		    
			$params['call_id'] = microtime(true);
			if ($params['call_id'] <= $this->last_call_id) {
			   $params['call_id'] = $this->last_call_id + 0.001;
			}
			$this->last_call_id = $params['call_id'];
			if (!isset($params['v'])) {
			  $params['v'] = '1.0';
			}
			$post_params = array();
			foreach ($params as $key => &$val) {
			  if (is_array($val)) $val = implode(',', $val);
			  $post_params[] = $key.'='.urlencode($val);
			}
			$secret = $this->secret;
			$post_params[] = 'sig='.$this->generate_sig($params, $secret);
			return implode('&', $post_params);
	}
	
	
	 public function post_request($method, $params) {	 	
			$post_string = $this->create_post_string($method, $params);
			//echo $this->server_addr.$post_string;
			//echo "post_string=$post_string";
			if (function_exists('curl_init')) {
				// Use CURL if installed...
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $this->server_addr);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_USERAGENT, 'Xiaonei API PHP5 Client 1.0 (curl) ' . phpversion());
				$result = curl_exec($ch);
				curl_close($ch);
			} else {
				// Non-CURL based version...
				$context =
				array('http' =>
				array('method' => 'POST',
				'header' => 'Content-type: application/x-www-form-urlencoded'."\r\n".
				'User-Agent: Xiaonei API PHP5 Client 1.0 (non-curl) '.phpversion()."\r\n".
				'Content-length: ' . strlen($post_string),
				'content' => $post_string));
				$contextid=stream_context_create($context);
				$sock=fopen($this->server_addr, 'r', false, $contextid);
				if ($sock) {
					$result='';
					while (!feof($sock))
					$result.=fgets($sock, 4096);
					fclose($sock);
				}
			}
			//echo "$result";
			return $result;
			
	}

	
	private function convert_xml_to_result($xml)
	{		
		  $sxml = simplexml_load_string($xml);
		  $result = self::convert_simplexml_to_array($sxml);          
          return $result;          
                              
	}		
	
	public static function convert_simplexml_to_array($sxml) {
    $arr = array();
    if ($sxml) {
      foreach ($sxml as $k => $v) {
        if ($sxml['list']) {
          $arr[] = self::convert_simplexml_to_array($v);
        } else {
          $arr[$k] = self::convert_simplexml_to_array($v);
        }
      }
    }
    if (sizeof($arr) > 0) {
      return $arr;
    } else {
      return (string)$sxml;
    }
    
    
  }
      
		
}

class XiaoneiRestClientException extends Exception {
	
	
}

/**
 * Error codes and descriptions for the Xiaonei API.
 */

class XiaoneiAPIErrorCodes {
  const API_EC_SUCCESS = 0;
}

?>